package com.das.mechanic_base.widget;

import android.content.Context;
import android.graphics.Color;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.das.mechanic_base.R;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.base.X3BaseBottomSheetDialog;
import com.das.mechanic_base.base.X3IBaseView;
import com.das.mechanic_base.bean.greendao.AloneServiceListBean;
import com.das.mechanic_base.bean.main.HomeMainCarBean;
import com.das.mechanic_base.mapi.api.NetWorkHttp;
import com.das.mechanic_base.mapi.response.HttpCallBack;
import com.das.mechanic_base.mapi.schedulers.RxSchedulersHelper;
import com.das.mechanic_base.utils.LanguageUtiles;
import com.das.mechanic_base.utils.SpHelper;
import com.das.mechanic_base.utils.X3DateUtils;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3TimeUtils;
import com.das.mechanic_base.utils.X3ToastUtils;
import com.umeng.analytics.MobclickAgent;
import com.yhao.floatwindow.IFloatWindow;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import static android.view.View.GONE;

public class X3BottomAffirmMileDialog extends X3BaseBottomSheetDialog implements View.OnClickListener, X3HomeTimeSelectDialog.IOnClickCar, X3HomeChangeMileDialog.IonClickChangeMile {

    private LinearLayout ll_time;
    private TextView tv_car_time_span;
    private TextView et_car_time;

    private LinearLayout ll_mile;
    private TextView tv_miles_span;
    private TextView et_miles;

    private TextView tv_cancel;
    private Button btn_next;
    private X3HomeTimeSelectDialog timeSelectDialog;
    private long workBaseId;
    private SimpleDateFormat endFormat,format;
    private SimpleDateFormat usEndFormat;
    private int newMiles;

    private String carModelTime = "";
    private SimpleDateFormat modelDate;
    private TextView tv_total;
    private String carCurrentMile;
    private int nextMiles;
    private String perMiles;
    private String km;
    private String moderYear;
    private boolean customSet;
    private int selectYear;
    private int selectMoth;
    private int newPerMiles;

    public X3BottomAffirmMileDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected boolean getDialogCancel() {
        return false;
    }

    @Override
    protected void initView() {
        km = (String) SpHelper.getData(X3Constent.MILEAGEUNIT, "km");
        ll_time = getView(R.id.ll_time);
        tv_car_time_span = getView(R.id.tv_car_time_span);
        et_car_time = getView(R.id.et_car_time);

        ll_mile = getView(R.id.ll_mile);
        tv_miles_span = getView(R.id.tv_miles_span);
        et_miles = getView(R.id.et_miles);

        tv_cancel = getView(R.id.tv_cancel);
        btn_next = getView(R.id.btn_next);
        tv_total = getView(R.id.tv_total);

        ll_mile.setOnClickListener(this);
        ll_time.setOnClickListener(this);
        tv_cancel.setOnClickListener(this);
        btn_next.setOnClickListener(this);

        endFormat = new SimpleDateFormat("yyyy-MM",Locale.CHINA);
        usEndFormat = new SimpleDateFormat("MMM, yyyy",Locale.ENGLISH);
        format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        modelDate = new SimpleDateFormat("yyyy-MM-dd");
    }

    public void setWorkBaseId(long workBaseId,HomeMainCarBean mainCarBean) {
        this.workBaseId = workBaseId;
        if (mainCarBean == null) {
            return;
        }
        String carProductionDate = mainCarBean.getCarProductionDate();
        String estimateCurrentMiles = mainCarBean.getEstimateCurrentMiles();

        if (!X3StringUtils.isEmpty(carProductionDate)) {

            et_car_time.setVisibility(View.VISIBLE);
            try {
                String format;
                if (LanguageUtiles.isZhRCN()) {
                    format = endFormat.format(this.format.parse(carProductionDate));
                }else {
                    format = usEndFormat.format(this.format.parse(carProductionDate));
                }
                carModelTime = modelDate.format(this.format.parse(carProductionDate));

                et_car_time.setText(format);

            } catch (ParseException e) {
                e.printStackTrace();
            }
            tv_car_time_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
            tv_car_time_span.setTextColor(Color.parseColor("#666666"));
        }else {
            carModelTime = "";
            et_car_time.setVisibility(GONE);
            tv_car_time_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
            tv_car_time_span.setTextColor(Color.parseColor("#333333"));
        }

//        String miles = StringUtils.isEmpty(estimateCurrentMiles) ? "" : estimateCurrentMiles;
//
//        if (StringUtils.isEmpty(miles)) {
//            et_miles.setText("");
//            et_miles.setVisibility(GONE);
//            tv_miles_span.setTextColor(Color.parseColor("#333333"));
//            tv_miles_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
//        }else {
//            et_miles.setVisibility(View.VISIBLE);
//            tv_miles_span.setTextColor(Color.parseColor("#666666"));
//            tv_miles_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
//            newMiles = (int) Double.parseDouble(miles);
//            et_miles.setText(newMiles + "");
//        }
        if (!X3StringUtils.isEmpty(mainCarBean.getCarProductionDate())) {
            et_car_time.setVisibility(View.VISIBLE);
            try {
                String format;
                if (LanguageUtiles.isZhRCN()) {
                    format  = endFormat.format(this.format.parse(mainCarBean.getCarProductionDate()));
                }else {
                    format = usEndFormat.format(this.format.parse(mainCarBean.getCarProductionDate()));
                }
                carModelTime = mainCarBean.getCarProductionDate();

                String selectFormat  = endFormat.format(this.format.parse(mainCarBean.getCarProductionDate()));
                String[] split = selectFormat.split("-");
                if (!X3StringUtils.isEmpty(split[0])) {
                    selectYear = Integer.parseInt(split[0]);
                }
                if (!X3StringUtils.isEmpty(split[1])) {
                    selectMoth = Integer.parseInt(split[1]);
                }

                et_car_time.setText(format);
                et_car_time.setTextColor(Color.parseColor("#333333"));

            } catch (ParseException e) {
                e.printStackTrace();
            }
            tv_car_time_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
            tv_car_time_span.setTextColor(Color.parseColor("#707380"));
        }else {
            carModelTime = "";
            et_car_time.setVisibility(GONE);
            tv_car_time_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
            tv_car_time_span.setTextColor(Color.parseColor("#B1B3BD"));
        }


        customSet = mainCarBean.getCustomSet();
        moderYear = mainCarBean.getCarProductionDate();
        String miles = X3StringUtils.isEmpty(mainCarBean.getEstimateCurrentMiles()) ? "" : mainCarBean.getEstimateCurrentMiles();
        if (X3StringUtils.isEmpty(miles)) {
            tv_total.setText("");
            carCurrentMile = "";
            tv_total.setVisibility(GONE);
            tv_miles_span.setTextColor(Color.parseColor("#B1B3BD"));
            tv_miles_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
        }else {
            tv_total.setVisibility(View.VISIBLE);
            tv_miles_span.setTextColor(Color.parseColor("#707380"));
            tv_miles_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
            nextMiles = (int) Double.parseDouble(miles);
            tv_total.setText(nextMiles + km);
            carCurrentMile = nextMiles + "";
        }
        perMiles = X3StringUtils.isEmpty(mainCarBean.getPerMiles()) ? "" : mainCarBean.getPerMiles();
        if (X3StringUtils.isEmpty(carCurrentMile) || "0".equals(carCurrentMile)){
            perMiles = "";
        }
        if (X3StringUtils.isEmpty(perMiles)) {
            et_miles.setText("");
            carCurrentMile = "";
            et_miles.setVisibility(GONE);
        }else {
            et_miles.setVisibility(View.VISIBLE);
            int permiles = (int) Double.parseDouble(perMiles);
            et_miles.setText(mContext.getResources().getString(R.string.x3_home_per_mile)+ " "+permiles +km);
        }
        checkStrEmpty();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.x3_bottom_affirm_mile_dialog;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_cancel) {
            dismiss();
        } else if (id == R.id.btn_next) {// 点击下一步
            if (X3StringUtils.isEmpty(et_miles.getText().toString())) {
                return;
            }
            if (X3StringUtils.isEmpty(carModelTime)) {
                return;
            }
            Map<String, Object> map = new HashMap<>();


            Date date = null;
            try {
                date = X3TimeUtils.stringToDate(carModelTime, "yyyy-MM-dd HH:mm:ss");
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String afterTime = simpleDateFormat.format(date);
                map.put("productDate", afterTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            double currentMiles = Double.parseDouble(carCurrentMile);
            map.put("currentMiles", (int) currentMiles);
            map.put("workBaseId", workBaseId);
            map.put("customPerMiles", (int) Double.parseDouble(perMiles));
            if (customSet) {
                map.put("customSet", customSet);
            }
            NetWorkHttp.getApi().updateCarProductionAndMiles(map)
                    .compose(RxSchedulersHelper.defaultComposeRequest())
                    .compose(((X3IBaseView) mContext).bindToLife())
                    .subscribe(new HttpCallBack<AloneServiceListBean>() {
                        @Override
                        protected void onDone(AloneServiceListBean serviceListBean) {
                            dismiss();
                            if (iOnClickSelectMile != null) {
                                iOnClickSelectMile.iOnSelectMiles();
                            }
                            if (serviceListBean == null) {
                                return;
                            }
                            if (iOnClickAffirmMiles != null) {
                                iOnClickAffirmMiles.iOnClickAffirm(currentMiles, serviceListBean.getPerMiles());
                            }
                        }

                        @Override
                        protected String LoadingMessage() {
                            return null;
                        }

                        @Override
                        protected void showError(String error) {

                        }
                    });
        } else if (id == R.id.ll_mile) {//                String input = et_miles.getText().toString();
//                int inputMile = 0;
//                if (!StringUtils.isEmpty(input)) {
//                    inputMile = (int) Double.parseDouble(input);
//                }
//                BottomMileChangeDialog mileChangeDialog = new BottomMileChangeDialog(mContext);
//                mileChangeDialog.show();
//                mileChangeDialog.showCurrentMiles(inputMile,newMiles);
//                mileChangeDialog.setiOnGetCurrentMile(miles -> {
//                    et_miles.setVisibility(View.VISIBLE);
//                    et_miles.setText(miles + "");
//                    tv_miles_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
//                    tv_miles_span.setTextColor(Color.parseColor("#666666"));
//                    checkStrEmpty();
//                });


            if (X3StringUtils.isEmpty(carModelTime)) {
                X3ToastUtils.showMessage(mContext.getString(R.string.x3_please_select_car_time));
                ll_time.performClick();
                return;
            }
            X3HomeChangeMileDialog changeMileDialog = new X3HomeChangeMileDialog(mContext);
            changeMileDialog.show();
            changeMileDialog.setOnSaveChangeMiles(this);
            if (X3StringUtils.isEmpty(carCurrentMile)) {
                carCurrentMile = "0";
            }
            changeMileDialog.showTotalAndTime((int) Double.parseDouble(carCurrentMile), moderYear, customSet, perMiles);
        } else if (id == R.id.ll_time) {
            if (timeSelectDialog == null) {
                timeSelectDialog = new X3HomeTimeSelectDialog(mContext);
            }
            timeSelectDialog.show();
            timeSelectDialog.setSelect(selectYear, selectMoth, mContext.getString(R.string.x3_delivery_time));
            timeSelectDialog.setiOnClick(this);
        }
    }

    /**
     * 检测按钮是否可以提交
     */
    private void checkStrEmpty() {
        boolean isEnable = !X3StringUtils.isEmpty(et_car_time.getText().toString()) && !X3StringUtils.isEmpty(et_miles.getText().toString());
        btn_next.setEnabled(isEnable);
        btn_next.setBackground(isEnable ? ContextCompat.getDrawable(mContext, R.drawable.x3_alone_dialog_affirm) : ContextCompat.getDrawable(mContext, R.drawable.x3_alone_point_bg));
    }

    @Override
    public void iOnClickSelect(String year, String month, String zhMonth) {
        boolean zhRCN = LanguageUtiles.isZhRCN();
        if (zhRCN) {
            et_car_time.setText(year + "-" + month);
        }else {
            et_car_time.setText(month + ", " + year);
        }

        selectYear = Integer.parseInt(year);
        selectMoth = Integer.parseInt(zhMonth);

        carModelTime = year + "-" + (selectMoth < 10 ? "0" + selectMoth : selectMoth) + "-01 00:00:00";
        moderYear = carModelTime;
        et_car_time.setVisibility(View.VISIBLE);
        et_car_time.setTextColor(Color.parseColor("#333333"));
        tv_car_time_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
        tv_car_time_span.setTextColor(Color.parseColor("#707380"));
        if(!X3StringUtils.isEmpty(carCurrentMile) && !customSet){
            getNowPerMiles((int) Double.parseDouble(carCurrentMile),moderYear);
        }
        checkStrEmpty();
        if (!X3StringUtils.isEmpty(carCurrentMile)) {
            return;
        }
        ll_mile.performClick();
    }

    IOnClickSelectMile iOnClickSelectMile;

    public void setiOnClickSelectMile(IOnClickSelectMile iOnClickSelectMile) {
        this.iOnClickSelectMile = iOnClickSelectMile;
    }
    public void getNowPerMiles(int totalMile,String modelTime) {//若当前里程和日均有值 选完日期后要重新计算日均里程 customSet =false
        if (!X3StringUtils.isEmpty(modelTime)) {
            int  days = X3DateUtils.getDayTimeAfter(modelTime);
           int newPerMiles = (int) (totalMile / days);
            if (newPerMiles > 1000) {
                newPerMiles = 1000;
            }

            tv_total.setVisibility(View.VISIBLE);
            tv_miles_span.setTextColor(Color.parseColor("#707380"));
            tv_miles_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
            nextMiles = totalMile;
            tv_total.setText(nextMiles + km);
            carCurrentMile = nextMiles + "";

            et_miles.setVisibility(View.VISIBLE);
            et_miles.setText(mContext.getResources().getString(R.string.x3_home_per_mile)+ " "+newPerMiles +km);
            perMiles = newPerMiles+"";
            customSet = false;

        }else {
            tv_total.setText("");
            carCurrentMile = "";
            tv_total.setVisibility(GONE);
            tv_miles_span.setTextColor(Color.parseColor("#B1B3BD"));
            tv_miles_span.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);

            et_miles.setText("");
            carCurrentMile = "";
            et_miles.setVisibility(GONE);
        }
    }
    @Override
    public void onSaveChangeMiles(String selectedTotalItemData, String selectedPerItemData, boolean onSaveChangeMiles) {
        et_miles.setVisibility(View.VISIBLE);
        tv_total.setVisibility(View.VISIBLE);
        tv_total.setText(selectedTotalItemData+" "+km);
        et_miles.setText(mContext.getResources().getString(R.string.x3_home_per_mile)+ " "+selectedPerItemData +km);
        carCurrentMile = selectedTotalItemData;
        perMiles = selectedPerItemData;
        customSet = onSaveChangeMiles;
        checkStrEmpty();
    }

    public interface IOnClickSelectMile {
        void iOnSelectMiles();

    }

    iOnClickAffirmMiles iOnClickAffirmMiles;

    public void setiOnClickAffirmMiles(X3BottomAffirmMileDialog.iOnClickAffirmMiles iOnClickAffirmMiles) {
        this.iOnClickAffirmMiles = iOnClickAffirmMiles;
    }

    public interface iOnClickAffirmMiles {
        void iOnClickAffirm(double currentMiles,double perMiles);
    }

    @Override
    protected void onStart() {
        super.onStart();
        MobclickAgent.onPageStart("确认日均行驶里程弹窗");
    }

    @Override
    protected void onStop() {
        super.onStop();
        MobclickAgent.onPageEnd("确认日均行驶里程弹窗");
    }
}
